//
//  EditViewController.m
//  VICKY ZONE
//
//  Created by sunx on 15/3/25.
//  Copyright (c) 2015年 sunx. All rights reserved.
//
#define SERVER @"http://samoyun.com/controller/mainController.php"
#import "EditViewController.h"
#import "TextViewCell.h"
#import "TextFieldCell.h"
#import "ClearCell.h"
#import "LoadImageCell.h"
#import "SVProgressHUD.h"
#import "NSURLSession+KKAddition.h"

#import "OSSClient.h"
#import "OSSTool.h"
#import "OSSData.h"
#import "OSSLog.h"

@interface EditViewController ()
@property(nonatomic,strong) NSString *type;
@property(nonatomic,strong) UIImagePickerController *imagePicker;
@property(nonatomic,strong) NSString *username;
@property(nonatomic,strong) NSMutableArray *imageURLs;
@property(nonatomic,strong) TextFieldCell *titleCell;
@property(nonatomic,strong) TextViewCell *bodyCell;
@property(nonatomic,strong) OSSBucket *bucket;
@end

@implementation EditViewController
- (instancetype)initWithType:(NSString *)type {
    self = [super init];
    self.type = type;
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    OSSClient *ossclient = [OSSClient sharedInstanceManage];
    NSString *accessKey = @"FNjUQUOIou5tLmjT";
    NSString *secretKey = @"nonrU2qLkukyPcqyEbXwAlUrcylH8G";
    NSString *yourBucket = @"vickyzone";
    
    [ossclient setGenerateToken:^(NSString *method, NSString *md5, NSString *type, NSString *date, NSString *xoss, NSString *resource){
        NSString *signature = nil;
        NSString *content = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@%@", method, md5, type, date, xoss, resource];
        signature = [OSSTool calBase64Sha1WithData:content withKey:secretKey];
        signature = [NSString stringWithFormat:@"OSS %@:%@", accessKey, signature];
        NSLog(@"here signature:%@", signature);
        return signature;
    }];
    [ossclient setGlobalDefaultBucketHostId:@"oss-cn-beijing.aliyuncs.com"];
    [ossclient setGlobalDefaultBucketAcl:PUBLIC_READ_WRITE];
    
    
    self.bucket = [[OSSBucket alloc] initWithBucket:yourBucket];
    [self.bucket setAcl:PUBLIC_READ_WRITE];
    [self.bucket setOssHostId:@"oss-cn-beijing.aliyuncs.com"];
    

    //CGRect rect = [ UIScreen mainScreen ].applicationFrame;
    //float width = rect.size.width;
    self.tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.username = [userDefault valueForKey:@"username"];
    self.imageURLs = [NSMutableArray new];
    
    NSLog(@"%@",self.type);
    self.view.backgroundColor = [UIColor colorWithRed:92.0/255.0 green:92.0/255.0 blue:92.0/255 alpha:0.9];
    
    ClearCell *clear = [[ClearCell alloc] initWithHeight:0.01];
    self.titleCell = [TextFieldCell new];
    
    self.titleCell.textField.placeholder = @"title";

    self.bodyCell = [[TextViewCell alloc] init];
    
    LoadImageCell *loadImage = [[LoadImageCell alloc] initWithString:@"添加图片"];
    loadImage.actionBlock = ^{
        [self makeActionSheetAppear];
    };
    LoadImageCell *submit = [[LoadImageCell alloc] initWithString:@"提交"];
    submit.actionBlock = ^{
        [self submit];
    };
    OrganicSection *mainSection = [OrganicSection sectionWithCells:@[clear, self.titleCell,clear,self.bodyCell]];
    
    
    OrganicSection *imageSection = [OrganicSection sectionWithCells:@[loadImage,submit]];
    imageSection.headerHeight = 20;
    imageSection.headerTitle = @"";

    self.sections = @[mainSection,imageSection];

}
#pragma mark - Action Sheet
- (void)makeActionSheetAppear {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Add Photo"
                                                             delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
                                                    otherButtonTitles:@"Take Photo", @"Choose From Library", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // the user clicked one of the OK/Cancel buttons
    if (buttonIndex == 0) {
        [self pushTakePhotoScreenInDelegate];
    }
    else if (buttonIndex == 1) {
        [self pushChoosePhotoScreenInDelegate];
    }
}

-(void)pushTakePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

-(void)pushChoosePhotoScreenInDelegate
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSLog(@"%@",timeString);
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filename = [NSString stringWithFormat:@"%@.png",timeString];
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent: filename];
    
    
    NSLog(@"path:%@ name:%@",filePath,filename);
    
    [SVProgressHUD show];
    NSData *data = UIImageJPEGRepresentation(image, 0.7);
    OSSData *uploadData = [[OSSData alloc] initWithBucket:self.bucket withKey:filename];
    [uploadData setData:data withType:@"image/png"];
    [uploadData uploadWithUploadCallback:^(BOOL isSuccess, NSError *error) {
        if(isSuccess) {
            NSString *imageUrl = [uploadData getResourceURL];
            [self.imageURLs addObject:imageUrl];
            [self performSelectorOnMainThread:@selector(HUDDismiss) withObject:self waitUntilDone:YES];

        }else {
            NSLog(@"error:%@",error);
            [self performSelectorOnMainThread:@selector(HUDDismiss) withObject:self waitUntilDone:YES];
        }
        
    } withProgressCallback:^(float progress) {
        NSLog(@"current get %f", progress);
        [SVProgressHUD dismiss];
    }];
    /*
    // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(image)writeToFile: filePath    atomically:YES];
    // 保存成功会返回YES
    if(result) {
        [NSURLSession Upload:filePath user:self.username type:@"blog" filename:filename progress:^(CGFloat progress) {
            
        } completed:^(NSData *data){
            
            
            NSString *image = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [self.imageURLs addObject:image];
            [self performSelectorOnMainThread:@selector(HUDDismiss) withObject:self waitUntilDone:YES];
        } failed:^(NSError *error) {
            if(error) {
                NSLog(@"%@",error);
            }
        }];
    }*/
}
- (void)submit {
    NSString *title;
    if([self.type isEqualToString:@"axis"]) {
        title = @"#axis";
    }else {
        title = self.titleCell.textField.text;
    }
    NSString *body = self.bodyCell.textView.text;
    NSMutableString *images = [NSMutableString new];
    for(int i = 0; i < [self.imageURLs count]; i ++) {
        [images appendString:self.imageURLs[i]];
            [images appendString:@" "];
    }
    NSDictionary *p = @{
                        @"user":self.username,
                        @"title":title,
                        @"body":body,
                        @"images":images
                        };
    [SVProgressHUD show];
    [NSURLSession POST:SERVER pararms:p completed:^(NSData *data) {
        NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        
        [self performSelectorOnMainThread:@selector(dismiss) withObject:self waitUntilDone:YES];
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
        [SVProgressHUD dismiss];
    }];
}
#pragma mark -
- (void)dismiss {
    [SVProgressHUD dismiss];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Complete" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [[self navigationController] popViewControllerAnimated:YES];
    [alert show];
}
- (void)HUDDismiss {
    [SVProgressHUD dismiss];
    NSString *message = [[NSString alloc] initWithFormat:@"have added %ld photo",(unsigned long)[self.imageURLs count]];
    for(int i = 0; i < [self.imageURLs count]; i ++) {
        NSLog(@"%@",self.imageURLs[i]);
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Complete" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
